class IssueController {

    def index = { redirect(action: list, params: params) }

    // the delete, save and update actions only accept POST requests
    def allowedMethods = [delete: 'POST', save: 'POST', update: 'POST', resolve: 'POST']

    def list = {
        if (!params.max) params.max = 10
        [issueList: Issue.list(params)]
    }

    def show = {
        def issue = Issue.get(params.id)

        if (!issue) {
            flash.message = "Issue not found with id ${params.id}"
            redirect(action: list)
        }
        else { return [issue: issue] }
    }

    def delete = {
        def issue = Issue.get(params.id)
        if (issue) {
            issue.delete()
            flash.message = "Issue ${issue} deleted"
            redirect(action: list)
        }
        else {
            flash.message = "Issue not found with id ${params.id}"
            redirect(action: list)
        }
    }

    def edit = {
        def issue = Issue.get(params.id)

        if (!issue) {
            flash.message = "Issue not found with id ${params.id}"
            redirect(action: list)
        }
        else {
            return [issue: issue]
        }
    }

    def update = {
        def issue = Issue.get(params.id)
        if (issue) {
            issue.properties = params
            if (!issue.hasErrors() && issue.save()) {
                flash.message = "Issue ${params} updated"
                redirect(action: show, id: issue.id)
            }
            else {
                render(view: 'edit', model: [issue: issue])
            }
        }
        else {
            flash.message = "Issue not found with id ${params.id}"
            redirect(action: edit, id: params.id)
        }
    }

    def create = {
        def issue = new Issue()
        issue.properties = params
        return ['issue': issue]
    }

    def save = {
        def issue = new Issue(params)
        if (!issue.hasErrors() && issue.save()) {
            flash.message = "Issue ${issue} created"
            redirect(action: show, id: issue.id)
        }
        else {
            render(view: 'create', model: [issue: issue])
        }
    }

    def resolve = {
        def issue = Issue.findById(params.id);

        assert issue
        assert issue.issueStatus == IssueStatus.OPEN || issue.issueStatus == IssueStatus.IN_PROGRESS

        issue.issueStatus = IssueStatus.RESOLVED

        assert issue.save()

        flash.message = "Issue ${issue} resolved"

        redirect(action: show, id: issue.id)
    }
}
